package com.godyao.mall.oauth.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author godyao
 * @date 2022/4/1
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier(value = "jwtTokenUserDetailsService")
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 接口放行
                .antMatchers("/oauth/logout", "/actuator/**", "/instances/**", "/test/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // 允许表单登录
                .formLogin()
                .loginProcessingUrl("/login")
                .permitAll()
                .and()
                // 禁用csrf
                .csrf()
                .disable();
    }

    /**
     * 密码加密算法
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 提前注入到IOC容器供OAuth使用
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 处理用户名密码验证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //从数据库中查询用户信息
        auth.userDetailsService(userDetailsService);

        // 从内存加载用户
        //auth.inMemoryAuthentication()
        //        .withUser("admin")
        //        .password(new BCryptPasswordEncoder().encode("123456"))
        //        .roles("admin")
        //        .and()
        //        .withUser("user")
        //        .password(new BCryptPasswordEncoder().encode("123456"))
        //        .roles("user");
    }

}
